package com.example.controller;

import com.example.entity.result.Result;
import com.example.entity.result.ResultBean;
import com.example.service.UserService;
import com.example.utils.DataUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;


/**
 * 登录注册控制
 */
@RestController
@RequestMapping("/login")
public class LoginController extends BaseHandleException {

    @Autowired
    private UserService userService;

    //登录
    @RequestMapping("/login")
    public ResultBean login(@RequestParam("username") String username,
                            @RequestParam("password") String password,
                            HttpServletRequest request) {
        Result result = userService.login(username, password);
        if (result.getCode() == Result.SUCCESS) {
            request.getSession().setAttribute("user", result.getMap().get("user"));
        }
        return DataUtils.getResultBean(result, "string");
    }

    //注册
    @RequestMapping("/register")
    public ResultBean register(@RequestParam("user") String json) {
        return DataUtils.getResultBean(userService.register(DataUtils.getUser(json)), "string");
    }
}
